<script lang="ts" setup>
import { ref, shallowRef } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import {
  loadOrganizationPositionPageApi,
  loadOrganizationPostPageApi,
  loadOrganizationRankPageApi,
  saveOrganizationMemberApi,
} from '#/api';
import {
  OrganizationDepartmentTreeSelect,
  OrganizationSelect,
} from '#/components';

defineOptions({
  name: 'OrganizationMemberDrawer',
});

const positionOptions = ref<Array<any>>([]);
const rankOptions = ref<Array<any>>([]);
const postOptions = ref<Array<any>>([]);
const organizationOptions = ref<Array<any>>([]);

const [Form, formApi] = useVbenForm({
  schema: [
    {
      component: shallowRef(OrganizationSelect),
      componentProps: {
        class: 'mr-2, w-full',
        initOptions: organizationOptions,
        onSelect: (value: string, option: any) => {
          formApi.setFieldValue('organizationName', option.label);
        },
      },
      fieldName: 'organizationId',
      label: $t('org.organization.title'),
      rules: 'required',
      description: '',
    },
    {
      component: shallowRef(OrganizationDepartmentTreeSelect),
      componentProps: {
        class: 'mr-2, w-full',
        onSelect: (value: any, option: any) => {
          formApi.setFieldValue('departmentName', option.label);
        },
      },
      fieldName: 'departmentId',
      label: $t('org.organizationDepartment.title'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'userId',
      label: $t('org.organizationMember.field.userId'),
      rules: '',
      description: '',
    },
    {
      component: 'DataDictRadioGroup',
      componentProps: {
        class: 'mr-2',
        dictType: 'MemberIdType',
      },
      fieldName: 'idType',
      label: $t('org.organizationMember.field.idType'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'idCode',
      label: $t('org.organizationMember.field.idCode'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'name',
      label: $t('org.organizationMember.field.name'),
      rules: 'required',
      description: '',
    },
    {
      component: 'DataDictRadioGroup',
      componentProps: {
        class: 'mr-2',
        dictType: 'MemberStatus',
      },
      fieldName: 'status',
      label: $t('org.organizationMember.field.status'),
      rules: 'required',
      description: '',
    },
    {
      component: 'DatePicker',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'birthday',
      label: $t('org.organizationMember.field.birthday'),
      rules: '',
      description: '',
    },
    {
      component: 'Select',
      componentProps: {
        class: 'mr-2 w-1/2',
        options: positionOptions,
        allowClear: true,
      },
      fieldName: 'positionName',
      label: $t('org.organizationMember.field.positionName'),
      rules: '',
      description: '',
    },
    {
      component: 'Select',
      componentProps: {
        class: 'mr-2 w-1/2',
        options: rankOptions,
        allowClear: true,
      },
      fieldName: 'rankCode',
      label: $t('org.organizationMember.field.rankName'),
      rules: '',
      description: '',
    },
    {
      component: 'Select',
      componentProps: {
        class: 'mr-2 w-1/2',
        options: postOptions,
        allowClear: true,
        mode: 'multiple',
      },
      fieldName: 'postCode',
      label: $t('org.post'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'phone',
      label: $t('org.organizationMember.field.phone'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'mobilePhone',
      label: $t('org.organizationMember.field.mobilePhone'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'address',
      label: $t('org.organizationMember.field.address'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'emergencyContactName',
      label: $t('org.organizationMember.field.emergencyContactName'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'emergencyContactPhone',
      label: $t('org.organizationMember.field.emergencyContactPhone'),
      rules: '',
      description: '',
    },
    {
      component: 'Textarea',
      componentProps: {
        class: 'mr-2',
        rows: 4,
      },
      fieldName: 'remark',
      label: $t('org.organizationMember.field.remark'),
      rules: '',
      description: '',
    },
  ],
  showDefaultActions: false,
  handleSubmit: onSubmit,
});

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    await formApi.submitForm();
    drawerApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, disabled } = drawerApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values);
        loadOrganizationPositionPageApi({
          size: 50,
        }).then((result) => {
          const items = result.records.map((item: any) => ({
            label: item.positionName,
            value: item.positionName,
          }));
          positionOptions.value.push(...items);
        });
        loadOrganizationRankPageApi({
          size: 50,
        }).then((result) => {
          const items = result.records.map((item: any) => ({
            label: item.rankName,
            value: item.rankCode,
          }));
          rankOptions.value.push(...items);
        });
        loadOrganizationPostPageApi({
          size: 50,
        }).then((result) => {
          const items = result.records.map((item: any) => ({
            label: item.postName,
            value: item.postCode,
          }));
          postOptions.value.push(...items);
        });
      }
      organizationOptions.value = values.organizationId
        ? [{ value: values.organizationId, label: values.organizationName }]
        : [];
      const enableEdit = !!disabled;
      formApi.setState({ commonConfig: { disabled: enableEdit } });
      drawerApi.setState({ showConfirmButton: !enableEdit });
    }
  },
  title: $t('org.organizationMember.title'),
});

async function onSubmit(values: any) {
  const rawData = drawerApi.getData().values;
  values.organizationMemberId = rawData.organizationMemberId;
  const rankOption = rankOptions.value.find(
    (item) => values.rankCode === item.value,
  );
  if (rankOption) {
    values.rankName = rankOption.label;
  }
  if (values.postCode && Array.isArray(values.postCode)) {
    const postNames: string[] = [];
    values.postCode.forEach((code: string) => {
      const match = postOptions.value.find((item) => item.value === code);
      if (match) {
        postNames.push(match.label);
      }
    });
    values.postName = postNames.join(',');
    values.postCode = values.postCode.join(',');
  }
  await saveOrganizationMemberApi(values);
  drawerApi.setData({ success: true });
}
</script>
<template>
  <Drawer class="w-[600px]">
    <Form />
  </Drawer>
</template>
